using System.Diagnostics;

namespace ChatClient
{
    public partial class NewsClient : Form
    {
        public NewsClient()
        {
            InitializeComponent();
            richTextBox.TextChanged += RichTextBox_TextChanged;
            richTextBox.LinkClicked += RichTextBox_LinkClicked;
            inputBox.KeyDown += InputBox_KeyDown;
            inputBox.TextChanged += InputBox_TextChanged;
        }

        private void InputBox_TextChanged(object? sender, EventArgs e)
        {
            var input = inputBox.Text;
            if (string.IsNullOrEmpty(input)) { return; }
            input = input.Trim();
            inputBox.Text = input;
        }

        private void InputBox_KeyDown(object? sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SendMessage();
            }
        }

        private void RichTextBox_LinkClicked(object? sender, LinkClickedEventArgs e)
        {
            //System.Diagnostics.Process.Start("msedge.exe", e.LinkText);
            var url = e.LinkText;
            url = url.Replace("&", "^&");
            Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
        }

        private void RichTextBox_TextChanged(object? sender, EventArgs e)
        {
            richTextBox.SelectionStart = richTextBox.Text.Length;
            richTextBox.ScrollToCaret();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            SendMessage();
        }

        private void SendMessage()
        {
            var question = inputBox.Text;
            Task task = Program.SendMessage(question, (answer) =>
            {
                RefreshMessages();
            });

            inputBox.Text = "";
        }

        public void RefreshMessages()
        {
            richTextBox.Text = Program.GetTalkHistory();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            Program.ClearHistory();
            richTextBox.Text = "";
        }
    }
}
